<?php

declare(strict_types=1);

namespace extend;

use extend\Request as ExtendRequest;
//使用方法
// $count = Staff::count();
// Page::setAttr($count, 200);
// $show = Page::show();
// $list = Staff::order('id', 'desc')->limit(Page::getFirstRow(), Page::getListRows())->select();
// foreach ($list as $k => $v) {
// }
// return View::fetch('',[
//     'list' => $list,
//     'page' => $show
// ]);
class Page
{
    // 分页栏每页显示的页数
    public $rollPage = 5;
    // 页数跳转时要带的参数
    public $parameter;
    // 分页URL地址
    public $url     =   '';
    // 默认列表每页显示行数
    public $listRows;
    // 起始行数
    public $firstRow = 0;
    // 分页总页面数
    protected $totalPages;
    // 总行数
    protected $totalRows = 0;
    // 当前页数
    protected $nowPage;
    // 分页的栏的总页数
    protected $coolPages;
    // 分页显示定制
    protected $config  =    array('header' => '条记录', 'prev' => '上一页', 'next' => '下一页', 'first' => '第一页', 'last' => '最后一页', 'theme' => ' %totalRow% %header% %nowPage%/%totalPage% 页 %upPage% %downPage% %first%  %prePage%  %linkPage%  %nextPage% %end%');
    // 默认分页变量名
    protected $varPage;
    //限制最多展示条数,超出则不显示页码,-1为不限制
    protected $maxShow = -1;

    /**
     * 架构函数
     * @access public
     * @param array $totalRows  总的记录数
     * @param array $listRows  每页显示记录数
     * @param array $parameter  分页跳转的参数
     */
    public function __construct($maxShow = -1)
    {
        $this->maxShow = $maxShow;
    }

    public function setConfig($name, $value)
    {
        if (isset($this->config[$name])) {
            $this->config[$name]    =   $value;
        }
    }
    public function setAttr($totalRows, $listRows)
    {
        $this->totalRows    =   $totalRows;
        $this->parameter    =   '';
        $this->varPage      =   'p';
        $this->listRows =   intval($listRows);
        $this->totalPages   =  ceil($this->totalRows / $this->listRows);     //总页数
        $this->coolPages    =   ceil($this->totalPages / $this->rollPage);
        $this->nowPage      =   !empty(ExtendRequest::param($this->varPage)) ? intval(ExtendRequest::param($this->varPage)) : 1;
        if ($this->nowPage < 1) {
            $this->nowPage  =   1;
        } elseif (!empty($this->totalPages) && $this->nowPage > $this->totalPages) {
            $this->nowPage  =   $this->totalPages;
        }
        $this->firstRow     =   intval($this->listRows * ($this->nowPage - 1));
    }
    public function getFirstRow(): int
    {
        return $this->firstRow;
    }
    public function getListRows(): int
    {
        return $this->listRows ?? 0;
    }
    /**
     * 分页显示输出
     * @access public
     */
    public function show()
    {
        if (0 == $this->totalRows) return '';
        // 添加一个检查，如果总记录数超过 $this->maxShow，那么就限制总页数为 $this->maxShow / 每页的记录数
        if ($this->totalRows > $this->maxShow && $this->maxShow != -1) {
            $this->totalPages = ceil($this->maxShow / $this->listRows);
        }
        $p              =   $this->varPage;
        $nowCoolPage    =   ceil($this->nowPage / $this->rollPage);
        // 分析分页参数
        if ($this->url) {
            $depr       =  '/';
            // $url        =   rtrim(U('/'.$this->url,'',false),$depr).$depr.'__PAGE__';
        } else {
            if ($this->parameter && is_string($this->parameter)) {
                parse_str($this->parameter, $parameter);
            } elseif (is_array($this->parameter)) {
                $parameter      =   $this->parameter;
            } elseif (empty($this->parameter)) {
                unset($_GET['_URL_']);
                $var =  ExtendRequest::param();
                if (empty($var)) {
                    $parameter  =   array();
                } else {
                    $parameter  =   $var;
                }
            }
            $parameter[$p]  =   '__PAGE__';
            $controller = request()->controller;
            //解析出来的控制器名称
            $controller = str_replace(['app\\controller\\', 'Controller'], '', $controller);
            $url = config('my_domain') . '/' . strtolower($controller) . '/' . request()->action . '?' . http_build_query($parameter);
            // $url            =   U('',$parameter);
        }
        //上下翻页字符串
        $upRow          =   $this->nowPage - 1;
        $downRow        =   $this->nowPage + 1;
        if ($upRow > 0) {
            $upPage     =   "<a href='" . str_replace('__PAGE__', (string)$upRow, $url) . "'>" . $this->config['prev'] . "</a>";
        } else {
            $upPage     =   '';
        }

        if ($downRow <= $this->totalPages) {
            $downPage   =   "<a href='" . str_replace('__PAGE__', (string)$downRow, $url) . "'>" . $this->config['next'] . "</a>";
        } else {
            $downPage   =   '';
        }
        // << < > >>
        if ($nowCoolPage == 1) {
            $theFirst   =   '';
            $prePage    =   '';
        } else {
            $preRow     =   $this->nowPage - $this->rollPage;
            $prePage    =   "<a href='" . str_replace('__PAGE__', (string)$preRow, $url) . "' >上" . $this->rollPage . "页</a>";
            $theFirst   =   "<a href='" . str_replace('__PAGE__', '1', $url) . "' >" . $this->config['first'] . "</a>";
        }
        if ($nowCoolPage == $this->coolPages) {
            $nextPage   =   '';
            $theEnd     =   '';
        } else {
            $nextRow    =   $this->nowPage + $this->rollPage;
            $theEndRow  =   $this->totalPages;
            // 如果当前页加上 rollPage 的值小于总页数，那么显示 "下XX页" 的链接
            if ($nextRow < $this->totalPages) {
                $nextPage   =   "<a href='" . str_replace('__PAGE__', (string)$nextRow, $url) . "' >下" . $this->rollPage . "页</a>";
            } else {
                $nextPage = '';
            }
            // $nextPage   =   "<a href='" . str_replace('__PAGE__', $nextRow, $url) . "' >下" . $this->rollPage . "页</a>";
            $theEnd     =   "<a href='" . str_replace('__PAGE__', (string)$theEndRow, $url) . "' >" . $this->config['last'] . "</a>";
        }
        // 1 2 3 4 5
        $linkPage = "";
        for ($i = 1; $i <= $this->rollPage; $i++) {
            $page       =   ($nowCoolPage - 1) * $this->rollPage + $i;
            $page = (string)$page;
            if ($page != $this->nowPage) {
                if ($page <= $this->totalPages) {
                    $linkPage .= "&nbsp;<a href='" . str_replace('__PAGE__', (string)$page, $url) . "'>&nbsp;" . $page . "&nbsp;</a>";
                } else {
                    break;
                }
            } else {
                if ($this->totalPages != 1) {
                    $linkPage .= "&nbsp;<span class='current'>" . $page . "</span>";
                }
            }
        }

        $select = '<select name="" id="page_num"  onchange="location=(\'' . $url . '/p/\'+$(this).val() )">';
        for ($i = 1; $i <= $this->totalPages; $i++) {
            if ($this->nowPage == $i) {
                $selected = 'selected';
            } else {
                $selected = '';
            }

            $select .= "<option value='" . $i . "'" . $selected . " >$i</option>";
        }
        $select .= "</select>";
        $pageStr     =   str_replace(
            array('%header%', '%nowPage%', '%totalRow%', '%totalPage%', '%upPage%', '%downPage%', '%first%', '%prePage%', '%linkPage%', '%nextPage%', '%end%', '%select%'),
            array($this->config['header'], $this->nowPage, $this->totalRows, $this->totalPages, $upPage, $downPage, $theFirst, $prePage, $linkPage, $nextPage, $theEnd, $select),
            $this->config['theme']
        );
        return $pageStr;
    }
}
